package com.ddc.study.feature.login;

import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.view.Gravity;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.Toast;

import com.ddc.study.R;
import com.ddc.study.base.MvpActivity;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import androidx.annotation.NonNull;
import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnEditorAction;
import butterknife.OnTextChanged;

/**
 * login activity
 *
 * @author lshun
 */
public class LoginActivity extends MvpActivity<LoginContract.IView, LoginContract.IPresenter>
        implements LoginContract.IView {
    @BindView(R.id.input_layout_username)
    TextInputLayout mUsernameInputLayout;

    @BindView(R.id.input_layout_password)
    TextInputLayout mPasswordInputLayout;

    @BindView(R.id.edt_username)
    TextInputEditText mEdtUsername;

    @BindView(R.id.edt_password)
    TextInputEditText mEdtPassword;

    @BindView(R.id.btn_go)
    Button mBtnGo;

    @BindView(R.id.btn_switch_mode)
    Button mBtnSwitchMode;

    private Animation mSharkAnim;

    //当前模式: true时表示登录模式, false表示注册模式
    private boolean mLoginMode = true;

    @Override
    protected LoginContract.IPresenter createPresenter() {
        return new LoginPresenter();
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_login;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSharkAnim = AnimationUtils.loadAnimation(this, R.anim.anim_shake);
//        mSharkAnim.setInterpolator(new CycleInterpolator(3));
    }

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        setLoginMode(savedInstanceState.getBoolean("loginMode"));
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean("loginMode", mLoginMode);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mEdtUsername.getAnimation() != null) {
            mEdtUsername.getAnimation().cancel();
        }
        if (mEdtPassword.getAnimation() != null) {
            mEdtPassword.getAnimation().cancel();
        }
    }

    @OnTextChanged(R.id.edt_username)
    void onUsernameChanged() {
        mUsernameInputLayout.setErrorEnabled(false);
    }

    @OnTextChanged(R.id.edt_password)
    void onPasswordChanged() {
        mPasswordInputLayout.setErrorEnabled(false);
    }

    @OnEditorAction(R.id.edt_password)
    boolean onPwdEditorAction(int id) {
        if (id == EditorInfo.IME_ACTION_GO) {
            clickGo();
            return true;
        }
        return false;
    }

    @OnClick(R.id.btn_go)
    void clickGo() {
        Editable editable = mEdtUsername.getText();
        String email = editable == null ? null : editable.toString();

        editable = mEdtPassword.getText();
        String password = editable == null ? null : editable.toString();

        if (mLoginMode) {
            mPresenter.login(email, password);
        } else {
            mPresenter.register(email, password, password);
        }
    }

    @OnClick(R.id.btn_switch_mode)
    void clickSwitchMode() {
        setLoginMode(!mLoginMode);
    }

    private void setLoginMode(boolean isLoginMode) {
        setTitle(isLoginMode ? R.string.user_login : R.string.user_register);
        mEdtPassword.setImeActionLabel(isLoginMode ? getString(R.string.login) : getString(R.string.register),
                EditorInfo.IME_ACTION_GO);
        //在横屏状态下，当前焦点在密码输入框时，失去焦点后重新获取来触发输入法更新显示ImeActionLabel
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE &&
                getWindow().getDecorView().findFocus().getId() == mEdtPassword.getId()) {
            mEdtUsername.requestFocus();
            new Handler(Looper.getMainLooper()).post(() -> mEdtPassword.requestFocus());
        }
        mBtnGo.setText(isLoginMode ? R.string.login : R.string.register);
        mBtnSwitchMode.setText(isLoginMode ? R.string.switch_register : R.string.switch_login);
        mLoginMode = isLoginMode;
    }

    @Override
    public void showUsernameError(String errorMsg) {
        mUsernameInputLayout.setErrorEnabled(true);
        mUsernameInputLayout.setError(errorMsg);
        mEdtUsername.requestFocus();
        mEdtUsername.startAnimation(mSharkAnim);
    }

    @Override
    public void showPasswordError(String errorMsg) {
        mPasswordInputLayout.setErrorEnabled(true);
        mPasswordInputLayout.setError(errorMsg);
        mEdtPassword.requestFocus();
        mEdtPassword.startAnimation(mSharkAnim);
    }

    @Override
    public void loginSuccess(@NonNull int[] collections) {
        hideSoftInput();
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void loginFailed(String errorMsg) {
        Toast toast = Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, -60);
        toast.show();
    }

    @Override
    public void registerSuccess() {
        Toast toast = Toast.makeText(getApplicationContext(), R.string.register_success_tip, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, -60);
        toast.show();

        hideSoftInput();
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void registerFailed(String errorMsg) {
        Toast toast = Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, -60);
        toast.show();
    }
}

